package com.link.base.base.user.controller;


import com.link.base.base.user.model.User;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.mvg.dao.mybatis.user.mapper.UserPostnMvgMapper;
import com.link.base.base.mvg.model.Mvg;
import com.link.base.base.mvg.service.MvgService;
import com.link.base.base.position.controller.MicroPositionController;
import com.link.base.base.position.model.ApiPosition;
import com.link.base.base.position.model.Position;
import com.link.base.base.position.service.PositionService;
import com.link.base.base.user.model.ApiUser;
import com.link.base.base.user.service.UserService;
import com.link.base.core.apiutils.ApiBasicController;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.LovUtil;
import com.link.core.util.PasswordUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  朱泊阳
 * @date:   2018/11/12 17:19
 * @version 1.0
 * @comment api工程迁入
 */

@Controller("UserApiController")
@RequestMapping("/linkApi/user")
public class MicroApiUserController extends ApiBasicController<User> {

    @Resource
    private MicroPositionController microPositionController;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private MvgService mvgService;

    @Resource
    private UserService userService;

    @Resource
    private UserPostnMvgMapper userPostnMvgMapper;

    @Resource
    private AccountService accountService;

    @Resource
    private PositionService positionService;

    @Override
    public BasicService<User> getBasicService() throws Exception {
        return userService;
    }

    @RequestMapping(value = "/upsert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsert(@RequestBody ApiUser model, HttpServletRequest request,
                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            User user = check(model);
            String postnIntegrationId = model.getPostnIntegrationId();
            List<Position> positionList = null;
            if (postnIntegrationId != null) {
                positionList = getPositionList(model);
            }
            //未匹配到linkcrm已有用户,新增用户
            if (user == null) {
                user = new User();
                ApiBasicController.apiCopyProperties(model, user);
                Long id = keyGenerateService.keyGenerate();
                //设置主要职位ID
                if (positionList != null && positionList.size() > 0) {
                    for (Position position : positionList) {
                        String integrationId = position.getIntegrationId();
                        if (postnIntegrationId.equals(integrationId)) {
                            Long postnId = position.getId();
                            user.setPostnId(postnId);
                            break;
                        }
                    }
                }
                Long dealerId = dealAccount(model);
                user.setAcctId(dealerId);
                user.setId(id);
                user.setSource("SIEBEL");
                String passwd = user.getPassword();
                String newPasswd = PasswordUtil.generatePwd(passwd);
                user.setPassword(newPasswd);
                //给一个默认的角色
                user.setRole("BJGX_PRESIDENT");
                user.setIntegrationId(model.getIntegrationId());
                userService.insert(user);
                //处理用户的职位信息
                if (positionList != null) {
                    setUserPostn(id, positionList, true);
                }
            } else {
                //已匹配到linkcrm已有客户,更新用户
                ApiBasicController.apiCopyProperties(model, user);
                //设置主要职位ID
                if (positionList != null && positionList.size() > 0) {
                    for (Position position : positionList) {
                        String integrationId = position.getIntegrationId();
                        if (postnIntegrationId.equals(integrationId)) {
                            Long postnId = position.getId();
                            user.setPostnId(postnId);
                            break;
                        }
                    }
                }

                Long dealerId = dealAccount(model);
                user.setAcctId(dealerId);
                user.setAnonymousFlag("Y");
                user.setIntegrationId(model.getIntegrationId());
                userService.update(user);
                //处理用户的职位信息
                if (positionList != null) {
                    setUserPostn(user.getId(), positionList, false);
                }
            }
            result.put("success", true);
            result.put("crmId", user.getId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * <p>检查该记录是否已存在，是则返回对象，否则返回null</p>
     *
     * @author wx
     * @param model
     * @return
     * @throws Exception
     */
    private User check(ApiUser model) throws Exception {
        //用戶集成ID不能为空
        //linkcrm userId
        Long id = model.getCrmId();
        //siebel userId
        String integrationId = model.getIntegrationId();
        //登录名
        String userName = model.getUsername();
        if (StringUtils.isBlank(integrationId)) {
            throw new BasicControllerException("集成Id不能为空");
        }
        User user = null;
        //crmId 为空则根据集成Id查询
        if (id == null) {
            QueryParams userQps = new QueryParams();
            userQps.addFilter(new Filter("integrationId", Filter.OP_EQUAL, integrationId));
            userQps.setPageFlag(false);
            User example = (User) BasicModel.transformClass(User.class, userQps);
            List<User> list = userService.queryByExamplePage(example);
            if (list == null || list.size() == 0) {
                //linkcrm中userName具有唯一性索引
                QueryParams userQps1 = new QueryParams();
                userQps1.addFilter(new Filter("username", Filter.OP_EQUAL, userName));
                userQps1.setPageFlag(false);
                User example1 = (User) BasicModel.transformClass(User.class, userQps1);
                List<User> list1 = userService.queryByExamplePage(example1);
                if (list1 != null && list1.size() > 0) {
                    throw new BasicControllerException("userName【" + userName + "】用户已存在");
                }
            } else if (list.size() == 1) {
                user = list.get(0);
            } else {
                throw new BasicControllerException("集成Id无法唯一确定一条记录");
            }
        } else {
            //crmId 不为空则根据crmId查询
            User example = new User();
            example.setId(id);
            user = userService.queryById(example);
            if (user == null) {
                throw new BasicControllerException("crmId【" + id + "】无法获取用户信息");
            } else if (!integrationId.equals(user.getIntegrationId())) {
                throw new BasicControllerException("集成Id不匹配");
            }
        }
        return user;
    }

    /**
     * <p>把api职位列表转换为职位列表</p>
     *
     * @author yrf
     * @param model
     * @return
     * @throws Exception
     */
    private List<Position> getPositionList(ApiUser model) throws Exception {
        List<ApiPosition> modelPostnList = model.getPostnList();
        if (modelPostnList == null || modelPostnList.size() == 0) {
            return null;
        } else {
            List<Position> postnList = new ArrayList<>(modelPostnList.size());
            for (int i = 0; i < modelPostnList.size(); i++) {
                ApiPosition postnModel = modelPostnList.get(i);
                Position postn = microPositionController.getPosition(postnModel);
                if (postn == null) {
                    throw new BasicControllerException("集成ID【" + postnModel.getIntegrationId() + "】无法获取职位信息");
                }
                postnList.add(postn);
            }
            return postnList;
        }
    }

    /**
     * <p>写入用户的职位到中间表</p>
     *
     * @author wx
     * @param id   linkcrm用戶ID
     * @param list siebel中用户的职位
     * @throws Exception
     */
    private void setUserPostn(Long id, List<Position> list, boolean isNew) throws Exception {

        // 修改 HuangLJ 2017年12月15日
        // 两边数据对比，将没匹配上的数据删除
        List<Position> origList = queryPositionByUserId(id);
        Iterator<Position> it = origList.iterator();
        while (it.hasNext()) {
            Position origItem = it.next();
            boolean existFlag = false;
            for (Position remoteItem : list) {
                if (StringUtils.equals(origItem.getIntegrationId(), remoteItem.getIntegrationId())) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag) {
                Mvg mvgParam = new Mvg();
                mvgParam.setMvgParentId(id);
                mvgParam.setMvgSubsetId(origItem.getId());
                userPostnMvgMapper.deleteById(mvgParam);
                it.remove();
            }
        }

        for (Position remoteItem : list) {
            boolean existFlag = false;
            for (Position origItem : origList) {
                if (StringUtils.equals(origItem.getIntegrationId(), remoteItem.getIntegrationId())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                continue;
            }
            Long crmId = remoteItem.getId();
            Position position = new Position();
            position.setId(crmId);
            Position ol = positionService.queryById(position);
            if (ol == null) {
                throw new BasicServiceException("职位Id【" + crmId + "】找不到职位！");
            }
            Mvg mvgParam = new Mvg();
            Long newId = keyGenerateService.keyGenerate();
            mvgParam.setId(newId);
            mvgParam.setMvgParentId(id);
            mvgParam.setMvgSubsetId(ol.getId());
            userPostnMvgMapper.insert(mvgParam);
        }
    }

    /**
     * @author huanglongjian
     * @param userId
     * @return
     * @throws Exception 通过用户Id查询职位信息
     */
    private List<Position> queryPositionByUserId(Long userId) throws Exception {
        Position positionQuery = new Position();
        positionQuery.setUserId(userId);
        positionQuery.setPageFlag(false);
        positionQuery.setTotalFlag(true);
        return positionService.queryByUserPage(positionQuery);
    }

    /**
     * <p>从中间表获取linkcrm用户的职位列表</p>
     *
     * @author wx
     * @return
     * @throws Exception
     */
    private List<String> getUserPostionList(Long userId) throws Exception {
        List<HashMap<String, String>> mvgObjList = new ArrayList<>();
        List<String> mvgList = new ArrayList<>();
        try {
            Mvg example = new Mvg();

            example.setMvgParentId(userId);
            mvgObjList = userPostnMvgMapper.queryLeftListPage(example);
            for (int i = 0; i < mvgObjList.size(); i++) {
                HashMap<String, String> mvgMap = mvgObjList.get(i);
                mvgList.add(mvgMap.get("id"));
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return mvgList;
    }

    /**
     * 获取得到对应用户的经销商Id
     *
     * @author 黄龙建
     * @date 2020/1/8 3:38 下午
     * @param model 传入的用户信息
     * @return 经销商ID
     */
    private Long dealAccount(ApiUser model) throws Exception {
        //HuangLJ 2017年11月30日 判断用户类型，内部用户，外部用户走不同逻辑
        String empType = model.getEmpType();
        String empTypeCode = LovUtil.getLovValue("EMP_TYPE", empType);
        String outerEmp = "OUTER_EMP";
        if (outerEmp.equals(empTypeCode)) {
            //外部用户，校验经销商
            Long acctId = model.getAcctId();
            Account accnt = new Account();
            accnt.setPageFlag(false);
            accnt.setTotalFlag(true);
            accnt.setIntegrationId(String.valueOf(acctId));
            accnt.setAcctType("DEALER1");
            List<Account> accntTmp = accountService.queryByExamplePage(accnt);
            if (accntTmp.size() < 1) {
                throw new Exception("通过经销商集成Id：【" + acctId + "】没有找到匹配的经销商！");
            }
            if (accntTmp.size() > 1) {
                throw new Exception("通过经销商集成Id：【" + acctId + "】找到多条匹配的经销商！");
            }
            return accntTmp.get(0).getId();
        } else {
            //内部用户
            return null;
        }
    }
}
